package com.yuyu.demo.spring4.annotation.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import com.yuyu.demo.spring4.annotation.controller.AnController;

/**
 * 使用动态代理来实现AOP
 * 1. 使用Proxy.newProxyInstance
 * 2. 实现InvocationHandler接口
 *
 */
public class MyCaculateProxy {
	
	//我要代理的对象：
	private HelloCaculate target;
	
	public MyCaculateProxy(HelloCaculate target) {
		super();
		this.target = target;
	}

	//返回对象：
	public HelloCaculate getCon() {
		HelloCaculate proxy = null;
		//代理
		//代理对象由哪个类加载器负责加载
		ClassLoader loader = target.getClass().getClassLoader();
		Class[] interfaces = new Class[] {HelloCaculate.class};
		
		//调用代理对象的处理器
		InvocationHandler handler = new InvocationHandler() {
			
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				//可以进行一些参数的调整等
				System.out.println("invoke...."+method.getName());
				//执行方法
				Object result = method.invoke(target,args);
				return result;
			}
		};
		
		proxy = (HelloCaculate) Proxy.newProxyInstance(loader, interfaces, handler);
		
		return proxy;
	}

}
